/**
 * 
 */
package cn.com.xf.utils.encode.impl;

import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.Cipher;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.com.xf.utils.encode.EncodeService;

/**
 * @author Administrator
 * 
 */
public class EncodeServiceRSAImpl implements EncodeService {

	private static Log logger = LogFactory.getLog(EncodeServiceRSAImpl.class);

	@Override
	public String decode2Str(String input) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int decode2Int(String input) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public long decode2Long(String input) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String encode(String input) {
		String result = "";
		try {
			result = rsaEncode(input.getBytes("utf8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public String encode(int input) {
		return null;
	}

	@Override
	public String encode(long input) {
		// TODO Auto-generated method stub
		return null;
	}

	private String rsaEncode(byte[] input) {
		try {
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
			keyPairGen.initialize(1024);
			KeyPair keyPair = keyPairGen.generateKeyPair();
			// PublicKey publicKey = new
			// keyPair = new KeyPair("abcd", "1234");

			// Generate keys
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

			byte[] result = encrypt(publicKey, input);
			byte[] de = decrypt(privateKey, result);

			StringBuilder ret = new StringBuilder(result.length << 1);
			for (int i = 0; i < result.length; i++) {
				ret.append(Character.forDigit((result[i] >> 4) & 0xf, 16));
				ret.append(Character.forDigit(result[i] & 0xf, 16));
			}

			return (ret.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {
		if (publicKey != null) {
			try {
				Cipher cipher = Cipher.getInstance("RSA");
				cipher.init(Cipher.ENCRYPT_MODE, publicKey);
				return cipher.doFinal(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	private byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {
		if (privateKey != null) {
			try {
				Cipher cipher = Cipher.getInstance("RSA");
				cipher.init(Cipher.DECRYPT_MODE, privateKey);
				return cipher.doFinal(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	protected String bytesToString(byte[] encrytpByte) {
		String result = "";
		for (Byte bytes : encrytpByte) {
			result += (char) bytes.intValue();
		}
		return result;
	}

}
